﻿using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Adopted;
using Medical.Api.Write.Application.Command.DepartmentManagement.Recycling;
using Medical.Api.Write.Application.Command.DepartmentManagement.Sign;
using Medical.Api.Write.Application.Command.DepartmentManagement.Use;
using Medical.Api.Write.Dto.DepartmentManagement;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace Medical.Api.Write.Controllers
{
    /// <summary>
    /// 科室管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentManagementController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<DepartmentManagementController> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="logger"></param>
        public DepartmentManagementController(IMediator mediator, ILogger<DepartmentManagementController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 领用申请添加
        /// </summary>
        /// <param name="touseTable">领用申请表实体</param>
        /// <returns>操作结果</returns>
        [HttpPost("adopted-no-dto")]
        public async Task<ApiResult<int>> AddAdoptedNoDto([FromBody] TouseTable touseTable)
        {
            if (touseTable == null)
            {
                logger.LogWarning("接收到空的领用申请数据");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "请求数据不能为空",
                    Data = 0
                };
            }
            
            try
            {
                AddAdoptedCommands cmd = new AddAdoptedCommands
                {
                    touseTable = touseTable
                };
                
                logger.LogInformation("接收到领用申请请求，直接使用实体对象");
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加领用申请时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"添加失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 删除领用申请
        /// </summary>
        /// <param name="adoptedId"></param>
        /// <returns></returns>
        [HttpDelete("deladoped")]
        public async Task<ApiResult<int>> DeleteAdoptedCommandAsync(int adoptedId)
        {
            try
            {
                DeleteAdoptedCommands cmd = new DeleteAdoptedCommands
                {
                    adoptedId = adoptedId
                };
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除领用申请时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"删除失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改领用申请和物品
        /// </summary>
        /// <param name="request">包含领用申请和物品列表的请求数据</param>
        /// <returns>操作结果</returns>
        [HttpPost("update-adopted")]
        public async Task<ApiResult<int>> UpdateAdoptedCommandAsync([FromBody] AdoptedRequestDto request)
        {
            if (request == null)
            {
                logger.LogWarning("接收到空的领用申请修改请求");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "请求数据不能为空",
                    Data = 0
                };
            }

            // 确保TouseTable不为空
            if (request.TouseTable == null)
            {
                logger.LogWarning("领用申请数据(TouseTable)为空");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "领用申请数据不能为空",
                    Data = 0
                };
            }

            try
            {
                // 将DTO转换为实体
                TouseTable touseEntity = request.TouseTable.ToEntity();
                
                UpdateAdoptedCommand cmd = new UpdateAdoptedCommand
                {
                    touseTable = touseEntity,
                    itemTables = request.ItemTables ?? new List<ItemTable>()
                };
                
                logger.LogInformation("接收到领用申请修改请求，物品数量：{ItemCount}", 
                    request.ItemTables?.Count ?? 0);
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改领用申请时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 领用申请状态修改
        /// </summary>
        /// <param name="command">修改状态命令</param>
        /// <returns>操作结果</returns>
        [HttpPost("updateStatus")]
        public async Task<ApiResult<int>> UpdateAdoptedStatusCommandAsync([FromBody] UpdateAdoptedStatusCommands command)
        {
            try
            {
                logger.LogInformation("接收到领用申请状态修改请求，ID：{Id}，状态：{Status}", 
                    command.Id, command.TouseStatus);
                    
                var result = await mediator.Send(command);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改领用申请状态时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"状态修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 修改签收表的状态
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost("updatesignStatus")]
        public async Task<ApiResult<int>> UpdateSignStatusCommandAsync([FromBody] UpdateSignStatusCommands cmd)
        {
            try
            {
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }        
        /// <summary>
        /// 使用表新增
        /// </summary>
        /// <param name="useTable">使用表实体</param>
        /// <returns>操作结果</returns>
        [HttpPost("use-no-dto")]
        public async Task<ApiResult<int>> AddUseNoDto([FromBody] UseTable useTable)
        {
            if (useTable == null)
            {
                logger.LogWarning("接收到空的使用表数据");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "请求数据不能为空",
                    Data = 0
                };
            }
            
            try
            {
                AddUseCommands cmd = new AddUseCommands
                {
                    useTable = useTable
                };
                
                logger.LogInformation("接收到使用表新增请求，直接使用实体对象");
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加使用表时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"添加失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        
        /// <summary>
        /// 修改使用表的状态
        /// </summary>
        /// <param name="cmd">修改状态命令</param>
        /// <returns>操作结果</returns>
        [HttpPost("updateuseStatus")]
        public async Task<ApiResult<int>> UpdateUseStatueCommandAsync([FromBody] UpdateUseStatueCommands cmd)
        {
            try
            {
                logger.LogInformation("接收到使用表状态修改请求，ID：{Id}，状态：{Status}", 
                    cmd.UseId, cmd.RegistrationStatue);
                
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改使用表状态时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"状态修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改使用表和物品
        /// </summary>
        /// <param name="request">包含使用表和物品列表的请求数据</param>
        /// <returns>操作结果</returns>
        [HttpPost("update-use")]
        public async Task<ApiResult<int>> UpdateUseCommandAsync([FromBody] UseRequestDto request)
        {
            try
            {
                // 记录原始请求数据，帮助排查问题
                logger.LogInformation("接收到使用表修改请求");
                
                if (request == null)
                {
                    logger.LogWarning("接收到空的使用表修改请求");
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = "请求数据不能为空",
                        Data = 0
                    };
                }

                // 确保UseTable不为空
                if (request.UseTable == null)
                {
                    logger.LogWarning("使用表数据(UseTable)为空");
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = "使用表数据不能为空",
                        Data = 0
                    };
                }

                // 将DTO转换为实体
                UseTable useEntity = request.UseTable.ToEntity();
                
                UpdateUseCommands cmd = new UpdateUseCommands
                {
                    useTable = useEntity,
                    itemTables = request.ItemTables ?? new List<ItemTable>()
                };
                
                logger.LogInformation("处理使用表修改请求，物品数量：{ItemCount}", 
                    request.ItemTables?.Count ?? 0);
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                // 详细记录异常信息
                logger.LogError(ex, "修改使用表时发生错误: {Message}", ex.Message);
                
                // 如果是JSON序列化异常，提供更详细的错误信息
                if (ex is System.Text.Json.JsonException jsonEx)
                {
                    logger.LogError("JSON序列化错误: {JsonError}", jsonEx.Message);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = $"JSON格式错误: {jsonEx.Message}",
                        Data = 0
                    };
                }
                
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        /// <summary>
        /// 删除使用功能
        /// </summary>
        /// <param name="useId"></param>
        /// <returns></returns>
        [HttpDelete("use-Delete")]
        public async Task<ApiResult<int>> DeleteUseCommandAsync(int useId)
        {
            try
            {
                DeleteUseCommands cmd = new DeleteUseCommands
                {
                    UseId = useId
                };
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除使用表时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"删除失败:{ex.Message}",
                    Data = 0
                };
                throw;
            }
        }
       
        /// <summary>
        /// 修改回收申请和物品
        /// </summary>
        /// <param name="request">包含回收申请和物品列表的请求数据</param>
        /// <returns>操作结果</returns>
        [HttpPost("update-recycling")]
        public async Task<ApiResult<int>> UpdateRecyclingCommandAsync([FromBody] RecyclingRequestDto request)
        {
            try
            {
                // 记录原始请求数据，帮助排查问题
                logger.LogInformation("接收到回收申请修改请求");
                
                if (request == null)
                {
                    logger.LogWarning("接收到空的回收申请修改请求");
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = "请求数据不能为空",
                        Data = 0
                    };
                }

                // 确保RecyclingTable不为空
                if (request.RecyclingTable == null)
                {
                    logger.LogWarning("回收申请数据(RecyclingTable)为空");
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = "回收申请数据不能为空",
                        Data = 0
                    };
                }

                // 将DTO转换为实体
                RecyclingTable recyclingEntity = request.RecyclingTable.ToEntity();
                
                UpdateRecyclingCommands cmd = new UpdateRecyclingCommands
                {
                    recyclingTable = recyclingEntity,
                    itemTables = request.ItemTables ?? new List<ItemTable>()
                };
                
                logger.LogInformation("处理回收申请修改请求，物品数量：{ItemCount}", 
                    request.ItemTables?.Count ?? 0);
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                // 详细记录异常信息
                logger.LogError(ex, "修改回收申请时发生错误: {Message}", ex.Message);
                
                // 如果是JSON序列化异常，提供更详细的错误信息
                if (ex is System.Text.Json.JsonException jsonEx)
                {
                    logger.LogError("JSON序列化错误: {JsonError}", jsonEx.Message);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.Fail,
                        Msg = $"JSON格式错误: {jsonEx.Message}",
                        Data = 0
                    };
                }
                
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        
        /// <summary>
        /// 修改回收申请状态
        /// </summary>
        /// <param name="cmd">修改状态命令</param>
        /// <returns>操作结果</returns>
        [HttpPost("update-recycling-status")]
        public async Task<ApiResult<int>> UpdateRecyclingStatusCommandAsync([FromBody] UpdateRecyclingStatusCommands cmd)
        {
            try
            {
                logger.LogInformation("接收到回收申请状态修改请求，ID：{Id}，状态：{Status}", 
                    cmd.RecyclingId, cmd.RecyclingStatus);
                
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改回收申请状态时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"状态修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }
        
        /// <summary>
        /// 回收申请添加
        /// </summary>
        /// <param name="recyclingTable">回收申请表实体</param>
        /// <returns>操作结果</returns>
        [HttpPost("recycling-no-dto")]
        public async Task<ApiResult<int>> AddRecyclingNoDto([FromBody] RecyclingTable recyclingTable)
        {
            if (recyclingTable == null)
            {
                logger.LogWarning("接收到空的回收申请数据");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = "请求数据不能为空",
                    Data = 0
                };
            }
            
            try
            {
                AddRecyclingCommands cmd = new AddRecyclingCommands
                {
                    recyclingTable = recyclingTable
                };
                
                logger.LogInformation("接收到回收申请请求，直接使用实体对象");
                    
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加回收申请时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"添加失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除回收申请
        /// </summary>
        /// <param name="recyclingId">回收申请ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("recycling-delete")]
        public async Task<ApiResult<int>> DeleteRecyclingCommandAsync(int recyclingId)
        {
            try
            {
                logger.LogInformation("接收到回收申请删除请求，ID：{0}", recyclingId);
                
                DeleteRecyclingCommands cmd = new DeleteRecyclingCommands
                {
                    RecyclingId = recyclingId
                };
                
                var result = await mediator.Send(cmd);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除回收申请时发生错误");
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Msg = $"删除失败: {ex.Message}",
                    Data = 0
                };
            }
        }
    }
}
